<template>
  <div class="equipment-container">
    <!-- 页面头部 -->
    <!-- <div class="page-header">
      <div class="header-title">
        <i class="el-icon-s-management"></i>
        <span>设备接收管理系统</span>
      </div>
      <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增接收</el-button>
    </div>-->
    <div class="out full_h">
      <!-- 工具栏 -->
      <div class="toolbar">
        <div class="search-group">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索报废编号..."
            prefix-icon="el-icon-search"
            class="search-input"
            clearable
          ></el-input>
          <el-select v-model="filterStatus" placeholder="状态筛选" clearable>
            <el-option label="完成接收" value="completed"></el-option>
            <el-option label="待报废" value="pending"></el-option>
            <el-option label="接报废" value="processing"></el-option>
          </el-select>
        </div>
        <el-button
          type="primary"
          icon="el-icon-search"
          @keydown.enter="handleSearch"
          @click="handleSearch"
        >搜索</el-button>
      </div>

      <!-- 表格区域 -->
      <div style="height: calc(100% - 82px);" class="table-container">
        <div class="table-header">
          <div class="table-title">
            <i class="el-icon-document"></i>
            <span>设备报废列表</span>
          </div>
          <div class="table-actions">
            <!-- <el-button icon="el-icon-download" @click="handleExport">导出数据</el-button> -->
            <el-button icon="el-icon-refresh" @click="handleRefresh">刷新</el-button>
            <el-button icon="el-icon-plus" @click="handleAdd">报废登记</el-button>
          </div>
        </div>
        <!-- <div
          class
          style="overflow-y:auto;height: calc(100% - 82px);box-sizing: border-box;padding: 15px;
}"
        >
          bis quam ab culpa ipsam explicabo rerum minus praesentium, voluptates sed voluptatibus possimus eligendi dolores distinctio a. Amet recusandae nostrum cum sint commodi at.
          Suscipit, accusamus? Voluptate provident porro, earum eos autem deserunt soluta iure ab rem corrupti aspernatur optio magni dignissimos assumenda quias officiis deserunt esse saepe in impedit quam hic. Sed?
          lorem*100
        </div>-->
        <div
          class="table-area"
          style="overflow-y:hidden;height: calc(100% - 82px - 75px);box-sizing: border-box;padding: 15px;
}"
        >
          <el-table :data="scrapList" stripe style="width: 100%;" height="100%">
            <el-table-column prop="scrapId" align="center" label="报废编号"></el-table-column>
            <el-table-column prop="totalCount" width="100px" label="合计数量" align="center"></el-table-column>
            <el-table-column prop="totalOriginalValue" align="center" label="合计原值"></el-table-column>
            <el-table-column prop="scrapDate" label="报废日期" align="center"></el-table-column>
            <el-table-column prop="status" label="状态" align="center"></el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button
                  @click="handleView(scope.row)"
                  type="text"
                  size="small"
                  class="look-btn-pre"
                >查看</el-button>
                <el-button
                  @click="handleTabEdit(scope.row)"
                  type="text"
                  size="small"
                  class="edit-btn-pre"
                >编辑</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 分页 -->
        <div class="pagination-container">
          <div class="pagination-info">共 {{ total }} 条记录，{{ Math.ceil(total / pageSize) }} 页</div>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            layout="sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </div>
      </div>
    </div>
    <div v-if="showDeviceSelection" class="modal-overlay">
      <DeviceSelection
        ref="deviceSelector"
        :title="'选择设备'"
        :categories="categoryList"
        :initial-mode="selectionMode"
        :initial-selected="preSelectedDevices"
        :confirm-button-text="'确认选择'"
        @confirm="handleDeviceConfirm"
        @cancel="showDeviceSelection = false"
        @selection-change="handleSelectionChange"
        @mode-change="handleModeChange"
        @category-change="handleCategoryChange"
      />
    </div>

    <!-- 新增 -->

    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :title="curMode>0?'编辑设备接收信息':'新增设备接收'"
      :visible.sync="isEditDialog"
      width="70%"
      :before-close="handleEditClose"
      :destroy-on-close="true"
    >
      <div class="edit-main flex col">
        <el-tabs v-model="currDialogTab" @tab-click="tabClickDialog">
          <el-tab-pane v-for="val in sourceTab" :name="val.name" :label="val.label" :key="val.name"></el-tab-pane>
          <!-- <el-tab-pane name="2" label="设备列表信息"></el-tab-pane> -->
        </el-tabs>
        <div class="out-basic-info padd-up-down-15" v-show="currDialogTab==1">
          <div class="basic-info padd-15 bg">
            <el-row>
              <el-form
                :model="baseForm"
                status-icon
                :rules="rulesBaseForm"
                ref="rulesBaseForm"
                label-width="150px"
                class="demo-ruleForm"
              >
                <el-col :span="8">
                  <el-form-item label="报废单号">
                    <el-input
                      :disabled="onReady||!notEdit"
                      type="text"
                      v-model="baseForm.scrapUnit"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="申请单位" prop="applyUnit">
                    <!-- <el-input
                      :disabled="true&&notEdit"
                      @focus="openDeviceSelect"
                      type="text"
                      v-model="baseForm.applyUnit"
                    ></el-input>-->
                    <el-select
                      :disabled="!notEdit"
                      v-model="baseForm.applyUnit"
                      placeholder="请选择..."
                    >
                      <el-option
                        v-for="item in reqUnits"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="报废日期">
                    <!-- <el-input :disabled="true&&notEdit" type="text" v-model="baseForm.scrapDate"></el-input> -->
                    <el-date-picker
                      :disabled="onReady||!notEdit"
                      style="width: 100%;"
                      v-model="baseForm.scrapDate"
                      type="date"
                      placeholder="选择日期"
                    ></el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="合计数量">
                    <el-input
                      @input="handleTotalQuantity"
                      :disabled="onReady||!notEdit"
                      type="text"
                      v-model.number="baseForm.totalQuantity"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="合计原值">
                    <el-input
                      :disabled="onReady||!notEdit"
                      type="text"
                      v-model.number="baseForm.totalOriginalValue"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="报废原因" prop="scrapReason">
                    <el-input :disabled="!notEdit" type="textarea" v-model="baseForm.scrapReason"></el-input>
                  </el-form-item>
                </el-col>
              </el-form>
            </el-row>
          </div>
        </div>
        <template v-if="currDialogTab==2">
          <div class="edit-tit flex fl-up-down-ct padd-up-rt-15">
            <!-- <span class="padd-lt">设备列表信息</span> -->
            <span></span>
            <button v-if="!isView" type="button" class="maint-btn" @click="addDeviceBox">+ 新增设备信息</button>
          </div>
          <div class="device-list padd-up-down-15 f1">
            <div v-if="baseForm.deviceList.length === 0" class="empty-state">
              <i>📋</i>
              <h3>暂无设备信息</h3>
              <p>请点击上方的新增设备按钮添加设备信息</p>
            </div>

            <div v-else v-for="(item, index) in baseForm.deviceList" :key="index" class="card bg">
              <div class="card-header">
                <div class="card-title">设备 {{ index + 1 }}</div>
                <div class="btn-group">
                  <button class="action-btn delete-btn" @click="removeDevice(index)">删除</button>
                </div>
              </div>
              <el-row>
                <el-form
                  :model="item"
                  status-icon
                  ref="ruleForm"
                  label-width="150px"
                  class="demo-ruleForm"
                >
                  <el-col :span="8">
                    <el-form-item label="集成设备卡编号">
                      <el-input
                        :disabled="!notEdit"
                        @focus="openDeviceSelect(item,index)"
                        type="text"
                        v-model="item.integratedDeviceCardNumber"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="财务编号">
                      <el-input
                        :disabled="true||!notEdit"
                        type="text"
                        v-model="item.financialNumber"
                      ></el-input>
                    </el-form-item>
                  </el-col>

                  <el-col :span="8">
                    <el-form-item label="启用日期">
                      <!-- <el-input :disabled="true&&notEdit" type="text" v-model="item.startDate"></el-input> -->
                      <el-date-picker
                        :disabled="onReady||!notEdit"
                        style="width: 100%;"
                        v-model="item.startDate"
                        type="date"
                        placeholder="选择日期"
                      ></el-date-picker>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="设备标识">
                      <el-input
                        :disabled="onReady||!notEdit"
                        type="text"
                        v-model="item.deviceLabel"
                      ></el-input>
                    </el-form-item>
                  </el-col>

                  <el-col :span="8">
                    <el-form-item label="设备原值">
                      <el-input
                        :disabled="onReady||!notEdit"
                        type="text"
                        v-model="item.deviceOriginalValue"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="在用地点" v-model="item.usageLocation">
                      <el-input
                        :disabled="onReady||!notEdit"
                        type="text"
                        v-model="item.usageLocation"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="累计折旧">
                      <el-input
                        type="text"
                        :disabled="!notEdit"
                        v-model="item.accumulatedDepreciation"
                      ></el-input>
                    </el-form-item>
                  </el-col>

                  <el-col :span="8">
                    <el-form-item label="净值">
                      <el-input :disabled="!notEdit" type="text" v-model="item.netValue"></el-input>
                    </el-form-item>
                  </el-col>
                </el-form>
              </el-row>
            </div>
          </div>
        </template>
        <div v-if="currDialogTab==3" style="min-height:280px">
          <div class style @click="triggerUpload" v-if="isUpload">
            <i
              class="el-icon-plus avatar-uploader-icon"
              style="font-size: 28px;border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;"
            ></i>
          </div>
          <div class="document-info-wrap" v-else>
            <div
              class="document-item flex flex-between"
              v-for="(file, index) in fileList"
              :key="index"
            >
              <a :href="file.url" target="_blank">{{ file.name}}</a>
              <div class="btns">
                <el-button
                  @click="handlePreviewUploadedFile(file)"
                  type="text"
                  size="small"
                  class="file-action-btn"
                  icon="el-icon-view"
                >预览</el-button>
                <el-button
                  @click="handleDeleteUploadedFile(index)"
                  type="text"
                  size="small"
                  class="file-action-btn"
                  icon="el-icon-delete"
                >删除</el-button>
              </div>
            </div>
            <!-- 如需添加更多单据，可复制上述document-item结构 -->
          </div>
        </div>
        <div style="box-size: border-box" class="modal-footer flex">
          <el-button v-if="isView" size="mini" @click="handleEditClose">取消</el-button>
          <template v-if="!isView">
            <el-button size="mini" @click="handleEditClose">取消</el-button>
            <el-button color="#1a4b8c" size="mini" @click="handleEditSave" type="primary">保存</el-button>
            <el-button color="#1a4b8c" size="mini" type="primary" @click="handleScrap">报废</el-button>
            <!-- <el-button @click="handleUpDoc" color="#1a4b8c" size="mini" type="primary">上传单据</el-button> -->
            <div class="upload-area">
              <el-upload
                action="#"
                class="upload"
                ref="upload"
                :auto-upload="false"
                :on-change="handleUpDoc"
                :limit="1"
                :on-exceed="handleExceed"
                :disabled="uploadDisabled"
                :file-list="selectedFiles"
              >
                <el-button :disabled="uploadDisabled" size="small" type="primary">上传单据</el-button>
              </el-upload>
            </div>
            <el-button @click="handleScrapComplete" color="#1a4b8c" size="mini" type="primary">完成报废</el-button>
          </template>
        </div>
      </div>
    </el-dialog>
    <!-- 随机配件对话框组件 -->
    <RandomPartsSelection
      :visible.sync="showPartsDialog"
      :initial-data="currentParts"
      @submit="handlePartsSubmit"
      @close="handlePartsClose"
    />

    <!-- 图片预览弹窗（修复：确保src绑定Base64地址） -->
    <el-dialog :destroy-on-close="true" :visible.sync="isPreview" title="图片预览" width="80%">
      <img
        width="100%"
        :src="preImageUrl"
        alt="预览图"
        style="max-height: 600px; object-fit: contain;"
      />
    </el-dialog>
  </div>
</template>

<script>
import DeviceSelection from "../components/devicepts.vue";
import RandomPartsSelection from "../components/randpartsPts.vue";
export default {
  name: "EquipmentManagement",
  components: { DeviceSelection, RandomPartsSelection },
  data() {
    return {
      isView: false,
      isPreview: false,
      preImageUrl: "",
      isUpload: false,
      onReady: true,
      curMode: 0,
      currDialogTab: "1",
      deviceCardNoRecord: {},
      showPartsDialog: false,
      // 随机配件
      andomAccessories: [],
      currentParts: [
        {
          name: "电池",
          model: "5号电池",
          enableDate: "2023-12-07",
          quantity: 10,
          remarks: "高性能碱性电池"
        },
        {
          name: "保护码",
          model: "标准型",
          enableDate: "2023-11-15",
          quantity: 5,
          remarks: "设备安全保护"
        }
      ],
      deviceIdCounter: 0,
      devices: [],
      // todo 新增
      statusMapp: {
        1: "运行中",
        2: "维修中",
        3: "待机中",
        4: "关机中"
      },
      isEditDialog: false,
      baseForm: {
        deviceList: []
      },
      rulesBaseForm: {
        scrapReason: [
          {
            required: true,
            message: "请填写报废原因",
            trigger: ["blur", "change"]
          }
        ],
        applyUnit: [
          {
            required: true,
            message: "请选择单位",
            trigger: ["blur", "change"]
          }
        ]
      },
      reqUnits: [
        {
          label: "部门1",
          value: "1"
        },
        {
          label: "部门2",
          value: "2"
        },
        {
          label: "部门3",
          value: "3"
        },
        {
          label: "部门4",
          value: "4"
        },
        {
          label: "部门5",
          value: "5"
        },
        {
          label: "部门6",
          value: "6"
        }
      ],
      realData: {
        baseForm: {
          value1: "11",
          value2: "22",
          value3: "33"
        },
        sonTableData: [
          {
            id: 1,
            data1: "s",
            datalist: "112",
            data3: "113",
            data4: "2023-11-10 00:00:00",
            data5: "2",
            data6: "1"
          },
          {
            id: 2,
            data1: "111",
            datalist: "111",
            data3: "111",
            data4: "2023-10-26 00:00:00",
            data5: "111",
            data6: "1"
          },
          {
            id: 3,
            data1: "11124",
            data2: "1231",
            data3: "124",
            data4: "2023-10-27 00:00:00",
            data5: "152",
            data6: "2"
          },
          {
            id: 4,
            data1: "111",
            datalist: "111",
            data3: "111",
            data4: "2023-10-26 00:00:00",
            data5: "111",
            data6: "1"
          },
          {
            id: 5,
            data1: "11124",
            data2: "1231",
            data3: "124",
            data4: "2023-10-27 00:00:00",
            data5: "152",
            data6: "2"
          }
        ],
        maintTableData: [
          {
            data1: "清洗",
            data2: "11",
            data3: "1",
            data4: ""
          },
          {
            data1: "清洗",
            data2: "11",
            data3: "",
            data4: ""
          }
        ]
      },

      // todo
      showDeviceSelection: false,
      selectionMode: "multiple",
      preSelectedDevices: ["EQ-2023-001"],
      selectedDevices: [],
      deviceList: [
        {
          id: "EQ-2023-001",
          name: "高精度示波器",
          category: "演示用设备",
          spec: "带宽: 1GHz, 采样率: 5GS/s, 通道: 4",
          status: "available"
        },
        {
          id: "EQ-2023-002",
          name: "工业机器人",
          category: "生产设备",
          spec: "负载: 20kg, 重复定位精度: ±0.05mm",
          status: "inuse",
          disabled: true
        },
        {
          id: "EQ-2023-003",
          name: "服务器集群",
          category: "x86服务器",
          spec: "CPU: 2×Xeon Gold, 内存: 256GB, 存储: 4TB SSD",
          status: "available"
        },
        {
          id: "EQ-2023-004",
          name: "恒温恒湿试验箱",
          category: "仪器及试验设备",
          spec: "温度范围: -40℃~150℃, 湿度范围: 20%~98%",
          status: "maintenance"
        },
        {
          id: "EQ-2023-005",
          name: "电动叉车",
          category: "运输工具",
          spec: "载重: 2.5吨, 起升高度: 3.5米, 电池: 48V/600Ah",
          status: "available"
        }
      ],
      categoryList: [
        { id: "all", name: "全部设备", icon: "fas fa-th-list" },
        { id: "demo", name: "演示用设备", icon: "fas fa-tv" },
        { id: "production", name: "生产设备", icon: "fas fa-industry" },
        { id: "electronic", name: "电子设备", icon: "fas fa-laptop" },
        { id: "server", name: "x86服务器", icon: "fas fa-server" },
        { id: "server1", name: "x86服务器1", icon: "fas fa-server" },
        { id: "server2", name: "x86服务器2", icon: "fas fa-server" },
        { id: "server3", name: "x86服务器3", icon: "fas fa-server" },
        { id: "server4", name: "x86服务器4", icon: "fas fa-server" },
        { id: "server5", name: "x86服务器5", icon: "fas fa-server" },
        { id: "server6", name: "x86服务器6", icon: "fas fa-server" },
        { id: "server7", name: "x86服务器7", icon: "fas fa-server" },
        { id: "server8", name: "x86服务器8", icon: "fas fa-server" },
        { id: "server9", name: "x86服务器9", icon: "fas fa-server" },
        { id: "server10", name: "x86服务器10", icon: "fas fa-server" },
        { id: "server11", name: "x86服务器11", icon: "fas fa-server" },
        { id: "server12", name: "x86服务器12", icon: "fas fa-server" },
        { id: "server13", name: "x86服务器13", icon: "fas fa-server" },
        { id: "server14", name: "x86服务器14", icon: "fas fa-server" },
        { id: "server15", name: "x86服务器15", icon: "fas fa-server" },
        { id: "server16", name: "x86服务器16", icon: "fas fa-server" }
      ],
      searchKeyword: "",
      filterStatus: "",
      dateRange: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 479,
      scrapList: [
        {
          scrapId: "BF202310051900",
          totalQuantity: 1,
          totalOriginalValue: 2,
          scrapDate: "2023-10-25 00:00:00",
          status: "scrapped",
          basicInfo: {
            scrapUnit: "", // 报废单位
            applyUnit: "", // 申请单位
            totalOriginalValue: 0, // 合计原值
            scrapDate: "", // 报废日期
            totalQuantity: 0, // 合计数量
            scrapReason: "到达使用年限", // 报废原因
            deviceList: [
              {
                integratedDeviceCardNumber: "桌面设备", // 集成设备卡编号
                financialNumber: "001007", // 财务编号
                startDate: "1901-01-01", // 启用日期
                deviceLabel: "演示用设备", // 设备标识
                deviceOriginalValue: 100, // 设备原值
                usageLocation: "", // 在用地点
                accumulatedDepreciation: 0, // 累计折旧
                netValue: 100 // 净值
              }
            ]
          }
        },

        {
          scrapId: "BF202310051955",
          totalQuantity: 1,
          totalOriginalValue: 0,
          scrapDate: "-",
          status: "pending",
          basicInfo: {
            scrapUnit: "", // 报废单位
            applyUnit: "", // 申请单位
            totalOriginalValue: "", // 合计原值
            scrapDate: "", // 报废日期
            totalQuantity: 100, // 合计数量
            scrapReason: "到达使用年限", // 报废原因
            deviceList: [
              {
                integratedDeviceCardNumber: "桌面设备", // 集成设备卡编号
                financialNumber: "001007", // 财务编号
                startDate: "1901-01-01", // 启用日期
                deviceLabel: "演示用设备", // 设备标识
                deviceOriginalValue: 100, // 设备原值
                accumulatedDepreciation: 0, // 累计折旧
                netValue: 100, // 净值
                usageLocation: ""
              }
            ]
          }
        },
        {
          scrapId: "BF202310051826",
          totalQuantity: 2,
          totalOriginalValue: 12,
          scrapDate: "2023-10-11 00:00:00",
          status: "scrapped",
          basicInfo: {
            scrapUnit: "", // 报废单位
            applyUnit: "", // 申请单位
            totalOriginalValue: "", // 合计原值
            scrapDate: "", // 报废日期
            totalQuantity: 100, // 合计数量
            scrapReason: "到达使用年限", // 报废原因
            deviceList: [
              {
                integratedDeviceCardNumber: "桌面设备", // 集成设备卡编号
                financialNumber: "001007", // 财务编号 暂时以这个为唯一值
                startDate: "1901-01-01", // 启用日期
                deviceLabel: "演示用设备", // 设备标识
                deviceOriginalValue: 100, // 设备原值
                accumulatedDepreciation: 0, // 累计折旧
                netValue: 100, // 净值
                usageLocation: ""
              }
            ]
          }
        }
      ],
      tableData: [
        {
          receiveNo: "JS20180522005",
          deviceName: "佳兆多功能数码综合机-2204AD",
          totalCount: 1,
          acceptanceDate: "2018-05-22 00:00:00",
          status: "完成验收"
        },
        {
          receiveNo: "JS201405310010",
          deviceName: "排龙池",
          totalCount: 301,
          acceptanceDate: "2014-05-31 00:00:00",
          status: "完成验收"
        },
        {
          receiveNo: "JS201405310011",
          deviceName: "广区型电",
          totalCount: 1,
          acceptanceDate: "2014-05-31 00:00:00",
          status: "完成验收"
        },
        {
          receiveNo: "JS201405310012",
          deviceName: "3#4#清水池",
          totalCount: 2805,
          acceptanceDate: "2014-05-31 00:00:00",
          status: "完成验收"
        },
        {
          receiveNo: "JS200904300005",
          deviceName: "铝合金板棒-6米",
          totalCount: 1,
          acceptanceDate: "2009-04-30 00:00:00",
          status: "完成验收"
        }
      ],
      sourceTab: [
        { label: "设备信息", name: "1" },
        { label: "设备列表信息", name: "2" }
      ],
      notEdit: true,
      selectedFiles: [],
      fileList: [],
      uploadDisabled: false,
      currIndex: 0
    };
  },
  methods: {
    handleTotalQuantity(e) {
      console.log("handleTotalQuantity-0", e);
    },
    handleScrap(e) {
      this.notEdit = false;
    },
    handleScrapComplete(e) {
      this.$refs.rulesBaseForm.validate(valid => {
        if (valid) {
          console.log("请求后端");
          this.$message.success("保存成功");
          this.isEditDialog = false;
        } else {
          this.$message.error("请填写完整信息");
        }
      });
    },
    handlePreview(e) {
      console.log("e-1", e);
    },
    handleRemove(e) {
      console.log("e-2", e);
    },
    beforeRemove(e) {
      console.log("e-3", e);
    },
    handleExceed(e) {
      console.log("e-4", e);
    },
    handleUpDoc(file, fileList) {
      console.log("触发的", file, "fileList:", fileList);
      this.selectedFiles = fileList;
      this.customRequest({ file });
      if (this.fileList.length !== 0) {
        this.isUpload = false;
      }
      const exists = this.sourceTab.some(tab => tab.name == 3);
      if (!exists) {
        this.sourceTab.push({ label: "单据信息", name: "3" });
      }
      this.currDialogTab = "3";
    },
    // 预览
    handlePreviewUploadedFile(e) {
      console.log(e, "预览-e", this.fileList);
      this.preImageUrl = this.fileList[0].base64;
      this.isPreview = true;
    },
    triggerUpload() {
      this.$refs.upload.$el.querySelector("input").click();
    },
    handleDeleteUploadedFile(e) {
      this.fileList.splice(e, 1);
      console.log("this.fileList", this.fileList);
      if (this.fileList.length === 0) {
        this.isUpload = true;
      }
      this.$message.success("文件删除成功");
    },
    fileToBase64(file) {
      return new Promise((resolve, reject) => {
        if (!(file instanceof File)) {
          reject(new Error("参数必须是一个File对象"));
          return;
        }
        const reader = new FileReader();
        reader.onload = function(event) {
          // 返回完整的Base64 Data URL，格式如：...
          resolve(event.target.result);
        };
        reader.onerror = function(error) {
          reject(new Error("文件读取失败: " + error));
        };

        // 读取文件为Data URL（包含Base64编码）
        reader.readAsDataURL(file);
      });
    },
    async customRequest({ file }) {
      const fileRaw = file.raw;
      let target = await this.fileToBase64(fileRaw);
      console.log("图片原始资源：", fileRaw);
      // -------- 模拟上传流程（实际项目替换为真实接口请求） --------
      const mockFileUrl = file.name;
      // 将上传成功的文件加入展示列表
      this.fileList.push({
        name: file.name,
        url: mockFileUrl,
        base64: target
      });
      // 从“选中列表”中移除该文件
      this.selectedFiles = this.selectedFiles.filter(f => f.uid !== file.uid);
      this.uploadDisabled = true;
    },

    tabClickDialog(e) {
      // this.currDialogTab = e._props.label;

      console.log("tabClickDialog-e", this.currDialogTab);
    },
    handleView(row) {
      this.baseForm = JSON.parse(JSON.stringify(row.basicInfo));
      this.isView = true;
      this.isEditDialog = true;
    },
    // 表格编辑
    handleTabEdit(row) {
      console.log("row", row);
      this.curMode = 1;
      this.isView = false;
      this.baseForm = JSON.parse(JSON.stringify(row.basicInfo));
      const exists = this.sourceTab.some(tab => tab.name == 3);
      if (!exists) {
        this.sourceTab.push({ label: "单据信息", name: "3" });
      }
      console.log(" this.baseForm ", this.baseForm);
      if (!this.fileList.length) {
        this.isUpload = true;
      }
      this.isEditDialog = true;
    },
    removeDevice(e) {
      this.deviceIdCounter -= 1;
      this.baseForm.totalQuantity = this.deviceIdCounter;
      console.log("this.deviceIdCounter -", this.deviceIdCounter);
      console.log(e, "this.baseForm.deviceList", this.baseForm.deviceList);
      this.baseForm.deviceList.splice(e, 1);
    },
    // 处理配件提交
    handlePartsSubmit(partsData) {
      console.log("提交的配件数据:", partsData);
      this.currentParts = partsData;
      this.$message.success("配件设置成功");
    },

    // 处理对话框关闭
    handlePartsClose() {
      console.log("配件对话框已关闭");
    },
    addDeviceBox() {
      console.log("1111:add", this.baseForm.deviceList);
      this.baseForm.deviceList.push({
        id: ++this.deviceIdCounter,
        integratedDeviceCardNumber: "", // 集成设备卡编号
        financialNumber: "", // 财务编号
        startDate: "", // 启用日期
        deviceLabel: "", // 设备标识
        deviceOriginalValue: "", // 设备原值
        accumulatedDepreciation: "", // 累计折旧
        netValue: "", // 净值
        usageLocation: ""
      });
      this.baseForm.totalQuantity = this.deviceIdCounter;
      console.log("this.deviceIdCounter  + ", this.deviceIdCounter);
      this.$nextTick(() => {
        const container = document.querySelector(".device-list");
        console.log("container", container);
        if (container) {
          container.scrollTo(0, 99999);
        }
      });
      console.log("1111111111", this.baseForm);
    },

    handleEditSave() {
      this.$refs.rulesBaseForm.validate(valid => {
        if (valid) {
          this.$message.success("保存成功");
          this.isEditDialog = false;
        } else {
          this.$message.error("请填写完整信息");
        }
      });
    },
    openDeviceSelect(row, i) {
      console.log("openDeviceSelect-row", row);
      this.currIndex = i;

      this.showDeviceSelection = true;
    },
    // todo 新增
    handleEditClose() {
      console.log("关闭编辑窗口", this.currDialogTab);
      this.currDialogTab = "1";
      this.$nextTick(() => {
        this.isEditDialog = false;
      });
    },
    // todo 新增
    handleDeviceConfirm(result) {
      console.log("设备选择确认:", result);
      this.baseForm.deviceList[this.currIndex] = {
        ...this.baseForm.deviceList[this.currIndex],
        ...result.devices[0]
      };
      console.log("row-after", this.baseForm.totalOriginalValue);
      this.baseForm.totalOriginalValue += this.baseForm.deviceList[
        this.currIndex
      ].deviceOriginalValue;
      this.showDeviceSelection = false;
    },

    handleSelectionChange(deviceIds) {
      console.log("选择变化:", deviceIds);
    },

    handleModeChange(mode) {
      console.log("模式变化:", mode);
      this.selectionMode = mode;
    },

    handleCategoryChange(categoryId) {
      console.log("分类变化:", categoryId);
    },

    // 通过ref调用子组件方法
    clearSelection() {
      this.$refs.deviceSelector.clearSelection();
    },

    setSelection(deviceIds) {
      this.$refs.deviceSelector.setSelection(deviceIds);
    },
    handleSearch() {
      console.log("搜索...");
      this.loading = true;
      setTimeout(() => {
        this.loading = false;
        this.$message.success("搜索完成");
      }, 500);
    },
    handleAdd() {
      const newBaseForm = { ...this.scrapList[0].basicInfo };
      Object.keys(newBaseForm).forEach(key => {
        if (key === "deviceList") {
          newBaseForm[key] = []; // deviceList 置为空数组
        } else if (typeof newBaseForm[key] === "string") {
          newBaseForm[key] = ""; // 字符串置为空字符串
        } else if (typeof newBaseForm[key] === "number") {
          newBaseForm[key] = 0; // 数字置为0
        } else if (typeof newBaseForm[key] === "boolean") {
          newBaseForm[key] = false; // 布尔值置为false
        } else {
          newBaseForm[key] = null; // 其他类型置为null
        }
      });
      this.baseForm = newBaseForm;
      this.isEditDialog = true;
      console.log("this.baseForm", this.baseForm);
    },
    handleClose(e) {
      this.isDialog1 = false;
    },

    handleExport() {
      this.$message.success("导出数据成功");
    },
    handleRefresh() {
      this.loading = true;
      setTimeout(() => {
        this.loading = false;
        this.$message.success("数据已刷新");
      }, 800);
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.loadData();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.loadData();
    },
    loadData() {
      this.loading = true;
      setTimeout(() => {
        this.loading = false;
      }, 500);
    }
  }
};
</script>

<style scoped lang="scss">
.equipment-container {
  height: 100%;
  width: 100%;
  padding: 15px;
  // width: 100%;
  box-sizing: border-box;
}

/* 头部区域 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  // margin-bottom: 24px;
  // padding: 0 8px;
}

.header-title {
  font-size: 24px;
  font-weight: 600;
  color: #1f2d3d;
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-title i {
  color: #409eff;
  font-size: 28px;
}

/* 搜索和操作区域 */
.toolbar {
  background: white;
  padding: 20px;
  // border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  // margin-bottom: 20px;
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
  .search-group {
    display: flex;
    gap: 12px;
    align-items: center;
    flex: 1;
    min-width: 300px;
  }

  .search-input {
    flex: 1;
    max-width: 400px;
  }
}

.filter-group {
  display: flex;
  gap: 12px;
  align-items: center;
}

/* 表格容器 */
.table-container {
  background: white;
  // border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  overflow: auto;
  min-height: 0;
}

.table-header {
  padding: 20px 24px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-title {
  font-size: 16px;
  font-weight: 600;
  color: #1f2d3d;
  display: flex;
  align-items: center;
  gap: 8px;
}

.table-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

/* 自定义表格样式 */
.custom-table {
  border: none;
}

.custom-table .el-table__header {
  // background: #f8f9fa;
}

.custom-table .el-table__header th {
  // background: #f8f9fa;
  color: #606266;
  font-weight: 600;
  border-bottom: 2px solid #eaeaea;
}

.custom-table .el-table__body tr:hover td {
  background: #f5f7fa !important;
}

.status-badge {
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-completed {
  background: #f0f9ff;
  color: #1890ff;
  border: 1px solid #d1e9ff;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.view-btn,
.edit-btn {
  padding: 6px 12px;
  border-radius: 6px;
  font-size: 12px;
  border: none;
  cursor: pointer;
  transition: all 0.3s;
}

.view-btn {
  background: #f0f9ff;
  color: #1890ff;
  border: 1px solid #d1e9ff;
}

.view-btn:hover {
  background: #1890ff;
  color: white;
}

.edit-btn {
  background: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

.edit-btn:hover {
  background: #52c41a;
  color: white;
}

/* 分页区域 */
.pagination-container {
  padding: 20px 24px;
  border-top: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fafbfc;
}

.pagination-info {
  color: #606266;
  font-size: 14px;
}

/* 统计卡片 */
.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
}

.stat-card {
  background: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  text-align: center;
}

.stat-value {
  font-size: 28px;
  font-weight: 600;
  color: #409eff;
  margin-bottom: 8px;
}

.stat-label {
  color: #606266;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .equipment-container {
    padding: 16px;
  }

  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }

  .toolbar {
    flex-direction: column;
    align-items: stretch;
  }

  .search-group {
    min-width: auto;
  }

  .stats-cards {
    grid-template-columns: 1fr;
  }
}
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10001;
}
// 新增
.edit-main {
  padding: 15px 15px 0;
  box-sizing: border-box;
  max-height: 80vh;
  .edit-tit {
    // border-left: 4px solid #1a4b8c;
    justify-content: space-between;
    font-size: 14px;
    font-weight: bold;
    color: #333;
    background: #fff9f9;
    padding-bottom: 15px;
    box-sizing: border-box;
  }
  .basic-info {
    border: 1px solid #ebeef5;
  }
  .edit-main-head {
    max-height: calc(80vh - 60px);
    // overflow-y:auto
  }
}
.abmain-maint-tle {
  overflow-y: auto;
  box-sizing: border-box;
}
.bg {
  // background-color: #f8f9fa;
}
.modal-footer {
  padding: 15px 20px;
  // background-color: #f8f9fa;
  justify-content: flex-end;
  gap: 10px;
  border-top: 1px solid #eaeaea;
  margin: 0 -15px;
  box-sizing: border-box;
}

// 设备列表
.device-list {
  background: white;
  // border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  overflow: auto;
  min-height: 0;
}
.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #7f8c8d;
}

.empty-state i {
  font-size: 48px;
  margin-bottom: 15px;
  color: #bdc3c7;
}
.card {
  // background: white;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  padding: 15px;
  margin-bottom: 10px;
  // border-left: 4px solid #3498db;
  animation: fadeIn 0.5s ease;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center !important;
  margin-bottom: 10px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eaeaea;
}

.card-title {
  font-size: 16px;
  color: #2c3e50;
  font-weight: 300;
}
.btn-group {
  display: flex;
  //   gap: 10px;
  justify-content: flex-end;
}
.action-btn {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 13px;
  transition: all 0.2s ease;
}

.delete-btn {
  background-color: #e74c3c;
  color: white;
}

.delete-btn:hover {
  background-color: #c0392b;
}
.edit-tit {
  // border-left: 4px solid #1a4b8c;
  justify-content: space-between;
  font-size: 14px;
  font-weight: bold;
  color: #333;
}
.maint-btn {
  background: none;
  border: 1px dashed #1a4b8c;
  color: #1a4b8c;
  cursor: pointer;
  font-size: 14px;
  padding: 7px 12px;
  border-radius: 4px;
  transition: background 0.2s;
}
/* 单据信息容器样式 */
.document-info-wrap {
  background-color: #eef5ff;
  border: 1px solid #c2d8ff;
  border-radius: 8px;
  padding: 16px;
  margin-top: 10px;
}
/* 单据项样式 */
.document-item {
  font-size: 14px;
  color: #333;
  line-height: 1.6;
}
.document-item a {
  color: var(--color-left-bg);
  text-decoration: none;
}
.document-item a:hover {
  text-decoration: underline;
}
</style>